﻿using System;
using System.Collections.Generic;
using Neo4jConnect.Traversal;
using Newtonsoft.Json.Linq;

namespace Neo4jConnect
{    
    public class Node : Neo4jElement
    {        
        private List<Relationship> relationships;
        
        public Relationship CreateRelationshipTo(Node otherNode, Enum relationshipType)
        {
            Relationship relationship = GraphDatabase.CreateRelationship(this, relationshipType.ToString(), otherNode);
            this.ResetRelations();
            otherNode.ResetRelations();
            return relationship;
        }

        internal void ResetRelations()
        {
            relationships = null;
        }

        public IEnumerable<Relationship> GetRelationships()
        {
            if (relationships == null)
            {
                relationships = new List<Relationship>();
                relationships.AddRange(GraphDatabase.GetRelationshipsOnNode(this.Id));
            }

            return relationships;
        }
        
        public IEnumerable<Node> Traverse(TraversalBuilder builder)
        {            
            return GraphDatabase.Traverse(this.Id, builder);
        }
     
        protected override void OnReadJson(JToken obj)
        {
            base.SelfUri = new Uri(obj.Value<string>("self"));
                        
            foreach (var prop in obj.Value<JObject>("data"))            
                this.SetProperty(prop.Key, prop.Value.Value<string>());            
        }

        public override void Save()
        {
            if (SelfUri == null)
            {
                GraphDatabase.CreateNode(this);
            }
            else
            {
                GraphDatabase.SetNodeProperties(this);
            }            
        }

        public override void Delete()
        {
            if (SelfUri != null)
                GraphDatabase.DeleteNode(base.Id);
        }

        public virtual void DeleteWithRelationships()
        {                       
            foreach (var relationship in GetRelationships())
                    relationship.Delete();
            
            Delete();
        }

        public override string ToString()
        {
            if (SelfUri == null)
                 return string.Format("v[]");
            else return string.Format("v[{0}]", Id);
        }
    }
}